#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>

int sem_create()
{
	int ret =0;
	ret = semget(IPC_PRIVATE, 1, 0600);
	if (ret == -1) {
		return -1;
	}
	return ret;
}

int sem_delete(int id)
{
	int ret = 0;
	struct sembuf sb;

	ret = semctl(id, 0, IPC_RMID);
	if (ret == -1)
		return -1;

	return 0;
}

int sem_up(int id, int val)
{
	int ret = 0;
	int nsops = 1;
	struct sembuf sb;

	sb.sem_op = val;
	sb.sem_flg = SEM_UNDO;
	sb.sem_num = 0;
	ret = semop(id,  &sb, nsops);
	if (ret == -1) {
		return -1;
	}
	return 0;
}

int sem_down(int id, int val)
{
	int ret = 0;
	struct sembuf sops;
	int nsops = 1;

	sops.sem_op = -val;
	sops.sem_flg = SEM_UNDO;
	sops.sem_num = 0;
	ret = semop(id,  &sops, nsops);
	if (ret == -1) {
		return -1;
	}
	return 0;
}

int init_sem(int val)
{
	int ret = 0;
	int semid = -1;

	semid = sem_create();
	if (semid == -1)
		return -1;

	ret = sem_up(semid, val);
	if (ret)
		return -1;

	return semid;
}

int init_PV()
{
	int ret = 0;

	ret = init_sem(1);
	if (ret == -1)
		return -1;

	return ret;
}

int delete_PV(int id)
{
	return sem_delete(id);
}

int sem_V(int id)
{
	int ret = 0;

	ret = sem_up(id, 1);
	if (ret)
		return -1;

	return 0;
}

int sem_P(int id)
{
	int ret = 0;

	ret = sem_down(id, 1);
	if (ret)
		return -1;

	return 0;
}

